﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Sinacor.Infra.Core.Licensing.Business;
using WebLicenseGenerator.UC;

namespace WebLicenseGenerator
{
	public partial class ManageCompanies : System.Web.UI.Page
	{
		Alias _aliasBusiness = null;
		List<Sinacor.Infra.Core.Licensing.Company> _selectedCompanyTable
		{
			get { return ViewState["FoundCompanyTable"] as List<Sinacor.Infra.Core.Licensing.Company>; }
			set { ViewState["FoundCompanyTable"] = value; }
		}
		List<Sinacor.Infra.Core.Licensing.Company> _availableCompanyTable
		{
			get { return ViewState["AvailableCompanyTable"] as List<Sinacor.Infra.Core.Licensing.Company>; }
			set { ViewState["AvailableCompanyTable"] = value; }
		}
		int _selectedAliasCode
		{
			get
			{
				if (ViewState["SelectedAliasCode"] != null)
					return Convert.ToInt32(ViewState["SelectedAliasCode"]);
				else
					return 0;
			}
			set { ViewState["SelectedAliasCode"] = value; }
		}
		CompanyInput _inputModal;

		void LoadAliases()
		{
			_aliasBusiness = new Alias();

			cbAliases.DataSource = _aliasBusiness.Selecionar(new Sinacor.Infra.Core.Licensing.Alias());
			cbAliases.DataTextField = "Nome";
			cbAliases.DataValueField = "ID";
			cbAliases.DataBind();
			cbAliases.Items.Insert(0, "");
		}

		void UpdateAttachedCompanies(Sinacor.Infra.Core.Licensing.Alias alias)
		{
			_aliasBusiness = new Alias();
			_aliasBusiness.AtualizarCompaniasVinculadas(alias);
		}

		void ClearNewCompanyForm()
		{
			txtCNPJ.Text = "";
			txtCompanyName.Text = "";
			txtCompanySinacorID.Text = "";
		}

		void ClearGridView()
		{
			grdAvailableCompanies.DataSource = null;
			grdSelectedCompanies.DataSource = null;

			this.BindGridView();
		}

		void BindGridView()
		{
			grdAvailableCompanies.DataBind();
			grdSelectedCompanies.DataBind();
		}

		void PrepareGridViewForInsert()
		{
			grdSelectedCompanies.DataSource = null;
			grdSelectedCompanies.DataBind();

			_aliasBusiness = new Alias();
			List<Sinacor.Infra.Core.Licensing.Company> companies = _aliasBusiness.SelecionarCompaniasNaoVinculadas(null);

			grdAvailableCompanies.DataSource = companies;
			_availableCompanyTable = companies;

			_selectedCompanyTable = new List<Sinacor.Infra.Core.Licensing.Company>();

			grdAvailableCompanies.DataBind();
		}

		void LockUnlockNewCompanyForm(bool isEnabled)
		{
			txtCNPJ.IsEnabled = isEnabled;
			txtCompanyName.IsEnabled = isEnabled;
			txtCompanySinacorID.IsEnabled = isEnabled;
			btInsertNewCompany.Enabled = isEnabled;
		}

		void grdSelectedCompanies_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			if (e.CommandName == "UpdateSelected" || e.CommandName == "UpdateAvailable")
			{
				int companyId = Convert.ToInt32(e.CommandArgument);
				Sinacor.Infra.Core.Licensing.Company selectedCompany = null;

				if (e.CommandName == "UpdateSelected")
				{
					foreach (Sinacor.Infra.Core.Licensing.Company company in _selectedCompanyTable)
					{
						if (company.CompanyId == companyId)
							selectedCompany = company;
						break;
					}
				}
				else if (e.CommandName == "UpdateAvailable")
				{
					foreach (Sinacor.Infra.Core.Licensing.Company company in _availableCompanyTable)
					{
						if (company.CompanyId == companyId)
							selectedCompany = company;
						break;
					}
				}

				if(selectedCompany != null)
					ShowCompanyInputDialog("Alteração de Empresa", "Altere os dados desejados", selectedCompany);
			}
		}

		void grdAvailableCompanies_RowUpdating(object sender, GridViewUpdateEventArgs e)
		{
		}

		void _inputModal_OnAction(object sender, InputEventArgs e)
		{
			if (e.Result == InputResult.Save)
			{
				this.RefreshGridView();
			}
		}

		bool ValidatePageFields()
		{
			return (txtCompanyName.IsValid && txtCNPJ.IsValid && txtCompanySinacorID.IsValid);
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				this.LoadAliases();
				this.LockUnlockNewCompanyForm(false);
			}

			_inputModal = ((WebLicenseGenerator.UC.CompanyInput)this.Master.FindControl("inputModal"));
			_inputModal.OnAction += new CompanyInput.InputEventHandler(_inputModal_OnAction);

			grdSelectedCompanies.RowCommand += new GridViewCommandEventHandler(grdSelectedCompanies_RowCommand);
			grdAvailableCompanies.RowCommand += new GridViewCommandEventHandler(grdSelectedCompanies_RowCommand);

			grdSelectedCompanies.RowUpdating += new GridViewUpdateEventHandler(grdAvailableCompanies_RowUpdating);
			grdAvailableCompanies.RowUpdating += new GridViewUpdateEventHandler(grdAvailableCompanies_RowUpdating);
		}

		protected void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			_selectedAliasCode = 0;

			DropDownList ddl = ((DropDownList)sender);

			if (ddl.SelectedIndex == 0)
			{
				this.ClearGridView();
				ddl.Focus();
				this.LockUnlockNewCompanyForm(false);
			}
			else
			{
				_selectedAliasCode = Int32.Parse(ddl.SelectedItem.Value);

				ddl.Items[0].Text = "";

				this.RefreshGridView();

				this.LockUnlockNewCompanyForm(true);
			}
		}

		protected void MoveItemsToLeft(object sender, EventArgs e)
		{
			bool atLeastOneChecked = false;

			foreach (GridViewRow r in grdAvailableCompanies.Rows)
			{
			    if (((CheckBox)r.Cells[0].FindControl("chkIsSelected")).Checked)
			    {
					atLeastOneChecked = true;

					//Verifica se deve criar ou nao um novo registro de Alias
					if (_selectedAliasCode == 0)
					{
						_aliasBusiness = new Alias();
						_selectedAliasCode = _aliasBusiness.Incluir(new Sinacor.Infra.Core.Licensing.Alias(cbAliases.SelectedItem.Text.Trim()));
					}

					foreach (Sinacor.Infra.Core.Licensing.Company company in _availableCompanyTable)
					{
						if (r.Cells != null && r.Cells[1] != null && !String.IsNullOrEmpty(r.Cells[1].Text))
						{
							if (company.CompanyId == Int32.Parse(r.Cells[1].Text))
							{
								Sinacor.Infra.Core.Licensing.Company newCompany = new Sinacor.Infra.Core.Licensing.Company(company.Name, company.LegalRegistrationId, company.CompanyId.Value);
								newCompany.SinacorCompanyId = company.SinacorCompanyId;

								_selectedCompanyTable.Add(newCompany);
								_availableCompanyTable.Remove(company);

								grdSelectedCompanies.DataSource = _selectedCompanyTable;
								grdAvailableCompanies.DataSource = _availableCompanyTable;

								this.BindGridView();

								break;
							}
						}
					}
			    }
			}

			if (atLeastOneChecked)
				this.UpdateAttachedCompanies(new Sinacor.Infra.Core.Licensing.Alias(_selectedAliasCode, _selectedCompanyTable));
		}

		protected void MoveItemsToRight(object sender, EventArgs e)
		{
			bool atLeastOneChecked = false;

			foreach (GridViewRow r in grdSelectedCompanies.Rows)
			{
				if (((CheckBox)r.Cells[0].FindControl("chkIsSelected")).Checked)
				{
					atLeastOneChecked = true;

					foreach (Sinacor.Infra.Core.Licensing.Company company in _selectedCompanyTable)
					{
						if (r.Cells != null && r.Cells[1] != null && !String.IsNullOrEmpty(r.Cells[1].Text))
						{
							if (company.CompanyId == Int32.Parse(r.Cells[1].Text))
							{
								Sinacor.Infra.Core.Licensing.Company newCompany = new Sinacor.Infra.Core.Licensing.Company(company.Name, company.LegalRegistrationId, company.CompanyId.Value);
								newCompany.SinacorCompanyId = company.SinacorCompanyId;

								_availableCompanyTable.Add(newCompany);
								_selectedCompanyTable.Remove(company);

								grdSelectedCompanies.DataSource = _selectedCompanyTable;
								grdAvailableCompanies.DataSource = _availableCompanyTable;

								this.BindGridView();

								break;
							}
						}
					}
				}
			}

			if (atLeastOneChecked)
				this.UpdateAttachedCompanies(new Sinacor.Infra.Core.Licensing.Alias(_selectedAliasCode, _selectedCompanyTable));
		}

		protected void InsertNewCompany(object sender, EventArgs e)
		{
			if (ValidatePageFields())
			{
				if (_selectedAliasCode == 0)
				{
					_aliasBusiness = new Alias();
					_selectedAliasCode = _aliasBusiness.Incluir(new Sinacor.Infra.Core.Licensing.Alias(cbAliases.SelectedItem.Text.Trim()));
				}

				Sinacor.Infra.Core.Licensing.Company newCompany = new Sinacor.Infra.Core.Licensing.Company(txtCompanyName.Text.Trim(), txtCNPJ.Number, 0);
				newCompany.SinacorCompanyId = txtCompanySinacorID.Number;

				_aliasBusiness = new Alias();
				_aliasBusiness.IncluirNovaCompanhia(new Sinacor.Infra.Core.Licensing.Alias(_selectedAliasCode), newCompany);

				_selectedCompanyTable.Add(newCompany);
				grdSelectedCompanies.DataSource = _selectedCompanyTable;
				grdAvailableCompanies.DataSource = _availableCompanyTable;

				this.BindGridView();
				this.ClearNewCompanyForm();
			}
		}

		void ShowMessageDialog(string title, string message)
		{
			WebLicenseGenerator.UC.Messaging messaging = ((WebLicenseGenerator.UC.Messaging)this.Master.FindControl("errorMessaging"));
			messaging.Message = message;
			messaging.Title = title;
			messaging.ShowMessageDialog();
		}

		void ShowCompanyInputDialog(string title, string message, Sinacor.Infra.Core.Licensing.Company company)
		{
			_inputModal.Title = title;
			_inputModal.Message = message;

			_inputModal.CompanyId = company.CompanyId.Value;
			_inputModal.CompanyCNPJ = company.LegalRegistrationId;
			_inputModal.CompanyName = company.Name;
			_inputModal.CompanySinacorId = company.SinacorCompanyId.Value.ToString();

			_inputModal.ShowInputDialog();
		}

		void RefreshGridView()
		{
			_aliasBusiness = new Alias();
			List<Sinacor.Infra.Core.Licensing.Company> selectedCompanies = _aliasBusiness.SelecionarCompaniasVinculadas(new Sinacor.Infra.Core.Licensing.Alias(_selectedAliasCode));
			List<Sinacor.Infra.Core.Licensing.Company> availableCompanies = _aliasBusiness.SelecionarCompaniasNaoVinculadas(new Sinacor.Infra.Core.Licensing.Alias(_selectedAliasCode));

			grdSelectedCompanies.DataSource = selectedCompanies;
			_selectedCompanyTable = selectedCompanies;

			grdAvailableCompanies.DataSource = availableCompanies;
			_availableCompanyTable = availableCompanies;

			this.BindGridView();
		}
	}
}